﻿using ManagementSystem.App_LocalResources;
using ManagementSystem.Areas.BMS.Models.User;
using ManagementSystem.Filter;
using ManagementSystem.Models;
using MS.Entities;
using MS.Enums.Common;
using MS.Identity;
using MS.Logic;
using MS.Utility.Common;
using MS.Utility.Config;
using MS.Utility.EF;
using MS.Utility.EnumHelper;
using MS.Utility.Files;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace ManagementSystem.Areas.BMS.Controllers
{
    [LoginFilter(Platform.BMS)]
    public class UserController : Controller
    {
        // GET: BMS/User
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult UserDetail()
        {
            long uid = Convert.ToInt64(RouteData.Values["id"]);
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            MS_UserCenter_UserAccount userAccount = userAccountLogic.GetItemByQuery(x => x.Uid == uid && x.Status >= (int)UserStatus.Normal);

            if (userAccount == null)
            {
                HttpContext.Response.Redirect("/BMS/Error/404");
            }

            return View(userAccount);
        }

        #region 变更头像
        /// <summary>
        /// 变更头像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ChangePortrait(long uid)
        {
            JsonResultModel model = new JsonResultModel();
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            MS_UserCenter_UserAttrLogic userAttrLogic = MS_UserCenter_UserAttrLogic.GetInstance();
            MS_UserCenter_UserAttr userAttr = userAttrLogic.GetItemByQuery(x => x.Uid == uid && x.Status >= (int)UserStatus.Normal);
            if (userAttr == null)
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = "未查询到用户信息";
                return Json(model);
            }
            if (HttpContext.Request.Files.Count == 0)
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = Message.PARAMERROR;
                return Json(model);
            }
            string portrait = userAttr.Portrait;
            HttpPostedFileBase file = HttpContext.Request.Files[0];
            string portraitPath = ConfigSetting.GetUserLogoPath();
            string dateUrl = DateTime.Now.ToString("yyyy-MM-dd");

            FileUtility.CreateFileDirectory(portraitPath, ConfigSetting.FileAccessType);
            string ext = Path.GetExtension(file.FileName);
            string filename = string.Format("{0}{1}", FileUtility.GetFileName(), ext);
            string savePath = Path.Combine(portraitPath, dateUrl, filename);
            FileUtility.WriteFile(savePath, file.InputStream);

            portrait = string.Format("{0}/{1}",  dateUrl, filename);
            long loginUid = SecurityIdentity.GetLoginUid();
            userAttr.Portrait = portrait;
            userAttr.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAttr.UpdateUid = loginUid;

            userAttrLogic.Save(userAttr);
            userAccountLogic.RemoveCache(userAttr.Uid);

            model.code = Code.SUCCESS;
            model.message = Message.SUCCESS;
            model.data = portrait;
            return Json(model);
        }
        #endregion

        #region 获取用户信息
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetUser(long uid)
        {
            JsonResultModel model = new JsonResultModel();
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            MS_UserCenter_UserAttrLogic userAttrLogic = MS_UserCenter_UserAttrLogic.GetInstance();

            MS_UserCenter_UserAccount userAccount = userAccountLogic.GetItemByQuery(x => x.Uid == uid && x.Status >= (int)UserStatus.Normal);
            MS_UserCenter_UserAttr userAttr = userAttrLogic.GetItemByQuery(x => x.Uid == uid && x.Status >= (int)UserStatus.Normal);

            if (userAccount == null)
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = "未查询到用户信息";
                return Json(model);
            }

            var data = new
            {
                portrait = ConfigSetting.GetUserLogoAbsoluteUrl(userAttr.Portrait),
                account = Utils.Htmls(userAccount.Account),
                phone = userAccount.Phone,
                email = Utils.Htmls(userAccount.Email),
                nickname = Utils.Htmls(userAttr.NickName),
                realname = Utils.Htmls(userAttr.RealName),
                gender = EnumHelper.GetEnumDescription((Gender)userAttr.Gender),
                birthday = DateTimeHelper.GetDateTime(userAttr.Birthday.ToString()).ToString("D"),
                registerTime = DateTimeHelper.GetDateTime(userAccount.CreateTime.ToString()).ToString("D"),
            };

            model.code = Code.SUCCESS;
            model.message = Message.SUCCESS;
            model.data = data;
            return Json(model);
        }
        #endregion

        #region 保存用户信息
        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="account"></param>
        /// <param name="phone"></param>
        /// <param name="email"></param>
        /// <param name="nickname"></param>
        /// <param name="realname"></param>
        /// <param name="gender"></param>
        /// <param name="birthday"></param>
        /// <returns></returns>
        public JsonResult Save(long uid, string account, string phone, string email, string nickname, string realname, int gender, DateTime birthday)
        {
            JsonResultModel model = new JsonResultModel();
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            MS_UserCenter_UserAttrLogic userAttrLogic = MS_UserCenter_UserAttrLogic.GetInstance();

            MS_UserCenter_UserAccount userAccount = userAccountLogic.GetItemByQuery(x => x.Uid == uid && x.Status >= (int)UserStatus.Normal);
            MS_UserCenter_UserAttr userAttr = userAttrLogic.GetItemByQuery(x => x.Uid == uid && x.Status >= (int)UserStatus.Normal);
            long loginUid = SecurityIdentity.GetLoginUid(Platform.BMS);
            if (userAccount == null || userAttr == null)
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = "未查询到用户信息";
                return Json(model);
            }

            if (string.IsNullOrEmpty(account) && string.IsNullOrEmpty(phone) && string.IsNullOrEmpty(email))
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = "账号、手机号或邮箱至少填一个。";
                return Json(model);
            }

            //唯一性校验
            if (!string.IsNullOrEmpty(account))
            {
                //判断Account是否唯一，若Account存在则直接返回已存在的uid
                MS_UserCenter_UserAccount tmpUserAccount = userAccountLogic.GetItemByQuery(x => x.Account == account && x.Uid != uid && x.Status >= (int)UserStatus.Normal);
                if (tmpUserAccount != null)
                {
                    model.code = Code.ERROR;
                    model.message = Message.ERROR;
                    model.data = "该账号已经存在";
                    return Json(model);
                }
            }
            if (!string.IsNullOrEmpty(email))
            {
                //判断Email是否唯一，若Email存在则直接返回已存在的uid
                MS_UserCenter_UserAccount tmpUserAccount = userAccountLogic.GetItemByQuery(x => x.Email == email && x.Uid != uid && x.Status >= (int)UserStatus.Normal);
                if (tmpUserAccount != null)
                {
                    model.code = Code.ERROR;
                    model.message = Message.ERROR;
                    model.data = "该邮箱已经存在";
                    return Json(model);
                }
            }
            if (!string.IsNullOrEmpty(phone))
            {
                //判断手机号是否唯一，若手机号存在则直接返回已存在的uid
                MS_UserCenter_UserAccount tmpUserAccount = userAccountLogic.GetItemByQuery(x => x.Phone == phone && x.Uid != uid && x.Status >= (int)UserStatus.Normal);
                if (tmpUserAccount != null)
                {
                    model.code = Code.ERROR;
                    model.message = Message.ERROR;
                    model.data = "该手机号已经存在";
                    return Json(model);
                }
            }

            userAccount.Account = account.Trim();
            userAccount.Phone = phone.Trim();
            userAccount.Email = email.Trim();
            userAccount.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAccount.UpdateUid = loginUid;

            userAttr.NickName = nickname.Trim();
            userAttr.RealName = realname.Trim();
            userAttr.Gender = gender;
            userAttr.Birthday = DateTimeHelper.GetTime(birthday);
            userAttr.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAttr.UpdateUid = loginUid;

            userAccountLogic.Save(userAccount);
            userAttrLogic.Save(userAttr);

            userAccountLogic.RemoveCache(userAccount.Uid);

            model.code = Code.SUCCESS;
            model.message = Message.SUCCESS;
            model.data = new { };
            return Json(model);
        }
        #endregion

        #region 获取用户列表
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="param">bootstraptable 分页查询基本参数</param>
        /// <param name="searchType">查询条件类型 0：uid查询，1用户名查询，2手机号查询，3昵称查询，4姓名查询</param>
        /// <param name="searchText">查询条件值</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetUserList(BootstrapTablePageParamModel param, int searchType, string searchText)
        {
            //bootstraptable 响应json数据模型
            PageListModel pageListModel = new PageListModel();
            int totalRecords = 0;
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            MS_UserCenter_UserAttrLogic userAttrLogic = MS_UserCenter_UserAttrLogic.GetInstance();

            List<MS_UserCenter_UserAttr> userAttrList = new List<MS_UserCenter_UserAttr>();
            //创建linq条件，根据参数进行条件组合
            Expression<Func<MS_UserCenter_UserAccount, bool>> expression = PredicateBuilder.True<MS_UserCenter_UserAccount>();
            expression = expression.And(x => x.Status >= (int)Status.Normal);
            if (!string.IsNullOrEmpty(searchText))
            {
                switch (searchType)
                {
                    //0：uid查询，1用户名查询，2手机号查询，3邮箱查询，4昵称查询，5姓名查询
                    case 0:
                        //uid
                        long tmp = 0;
                        long.TryParse(searchText, out tmp);
                        expression = expression.And(x => x.Uid == tmp);
                        break;
                    case 1:
                        //用户名
                        expression = expression.And(x => x.Account.Contains(searchText));
                        break;
                    case 2:
                        //手机号
                        expression = expression.And(x => x.Phone.Contains(searchText));
                        break;
                    case 3:
                        //邮箱
                        expression = expression.And(x => x.Email.Contains(searchText));
                        break;
                    case 4:
                        //昵称
                        userAttrList = userAttrLogic.GetListByQuery(x => x.NickName.Contains(searchText) && x.Status == (int)Status.Normal, null, false);
                        if (userAttrList.Count > 0)
                        {
                            List<long> uids = (from o in userAttrList select o.Uid).ToList();
                            expression = expression.And(x => uids.Contains(x.Uid));
                        }
                        else
                        {
                            expression = expression.And(x => x.Uid == -1);
                        }

                        break;
                    case 5:
                        //姓名
                        userAttrList = userAttrLogic.GetListByQuery(x => x.RealName.Contains(searchText) && x.Status == (int)Status.Normal, null, false);
                        if (userAttrList.Count > 0)
                        {
                            List<long> uids = (from o in userAttrList select o.Uid).ToList();
                            expression = expression.And(x => uids.Contains(x.Uid));
                        }
                        else
                        {
                            expression = expression.And(x => x.Uid == -1);
                        }
                        break;
                }
            }

            List<MS_UserCenter_UserAccount> userAccountList = userAccountLogic.GetPagedList(param.offset, param.limit, expression, param.sort, param.sortOrder == "desc", out totalRecords);

            if (userAttrList.Count == 0)
            {
                List<long> uids = (from o in userAccountList select o.Uid).ToList();
                userAttrList = userAttrLogic.GetListByQuery(x => uids.Contains(x.Uid), null, false);
            }
            var tableJson = from userAccount in userAccountList
                            join userAttr in userAttrList.DefaultIfEmpty() on userAccount.Uid equals userAttr.Uid
                            select new
                            {
                                uid = userAccount.Uid,
                                account = Utils.Htmls(userAccount.Account),
                                phone = Utils.Htmls(userAccount.Phone),
                                nickname = Utils.Htmls(userAttr.NickName),
                                realname = Utils.Htmls(userAttr.RealName),
                                gender = EnumHelper.GetEnumDescription((Gender)userAttr.Gender),
                                portrait = ConfigSetting.GetUserLogoAbsoluteUrl(userAttr.Portrait),
                                registTime = DateTimeHelper.GetDateTime(userAccount.CreateTime.ToString()).ToString("yyyy-MM-dd HH:mm:ss"),
                                status = userAccount.Status,
                                email = userAccount.Email

                            };
            if (totalRecords > 0)
            {
                pageListModel.rows = tableJson;
            }
            else
            {
                pageListModel.rows = userAccountList;
            }
            pageListModel.total = totalRecords;


            return Json(pageListModel);
        }
        #endregion

        #region 新增用户
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="account"></param>
        /// <param name="phone"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Add(string account, string phone, string email)
        {
            JsonResultModel model = new JsonResultModel();
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            MS_UserCenter_UserAttrLogic userAttrLogic = MS_UserCenter_UserAttrLogic.GetInstance();

            long loginUid = SecurityIdentity.GetLoginUid(Platform.BMS);

            if (string.IsNullOrEmpty(account) && string.IsNullOrEmpty(phone) && string.IsNullOrEmpty(email))
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = "账号、手机号或邮箱至少填一个。";
                return Json(model);
            }
            MS_UserCenter_UserAccount userAccount = new MS_UserCenter_UserAccount();
            MS_UserCenter_UserAttr userAttr = new MS_UserCenter_UserAttr();
            userAccount.Account = account.Trim();
            userAccount.Phone = phone.Trim();
            userAccount.Email = email.Trim();
            userAccount.Passformat = (int)Passformat.Encrypt;
            userAccount.Password = ConfigSetting.DefaultPassword;
            userAccount.CreateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAccount.CreateUid = loginUid;
            userAccount.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAccount.UpdateUid = loginUid;

            userAttr.NickName = Utils.GetRandomName();
            userAttr.RealName = Utils.GetRandomName();
            userAttr.CreateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAttr.CreateUid = loginUid;
            userAttr.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAttr.UpdateUid = loginUid;

            //唯一性校验
            if (!string.IsNullOrEmpty(userAccount.Account))
            {
                //判断Account是否唯一，若Account存在则直接返回已存在的uid
                MS_UserCenter_UserAccount tmpUserAccount = userAccountLogic.GetItemByQuery(x => x.Account == userAccount.Account && x.Status >= (int)UserStatus.Normal);
                if (tmpUserAccount != null)
                {
                    model.code = Code.ERROR;
                    model.message = Message.ERROR;
                    model.data = "该账号已经存在";
                    return Json(model);
                }
            }
            if (!string.IsNullOrEmpty(userAccount.Email))
            {
                //判断Email是否唯一，若Email存在则直接返回已存在的uid
                MS_UserCenter_UserAccount tmpUserAccount = userAccountLogic.GetItemByQuery(x => x.Email == userAccount.Email && x.Status >= (int)UserStatus.Normal);
                if (tmpUserAccount != null)
                {
                    model.code = Code.ERROR;
                    model.message = Message.ERROR;
                    model.data = "该邮箱已经存在";
                    return Json(model);
                }
            }
            if (!string.IsNullOrEmpty(userAccount.Phone))
            {
                //判断手机号是否唯一，若手机号存在则直接返回已存在的uid
                MS_UserCenter_UserAccount tmpUserAccount = userAccountLogic.GetItemByQuery(x => x.Phone == userAccount.Phone && x.Status >= (int)UserStatus.Normal);
                if (tmpUserAccount != null)
                {
                    model.code = Code.ERROR;
                    model.message = Message.ERROR;
                    model.data = "该手机号已经存在";
                    return Json(model);
                }
            }

            long uid = userAccountLogic.CreateUser(userAccount, userAttr);

            model.code = Code.SUCCESS;
            model.message = Message.SUCCESS;
            model.data = uid;
            return Json(model);
        }
        #endregion

        #region 删除用户
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="uids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Delete(List<long> uids)
        {
            JsonResultModel model = new JsonResultModel();
            if (uids == null)
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = Message.PARAMERROR;
                return Json(model);
            }
            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            long loginUid = SecurityIdentity.GetLoginUid(Platform.BMS);
            userAccountLogic.Delete(uids, loginUid);

            model.code = Code.SUCCESS;
            model.message = Message.SUCCESS;
            model.data = new { };
            return Json(model);
        }
        #endregion

        #region 重置密码
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ResetPassword(long uid)
        {
            JsonResultModel model = new JsonResultModel();

            MS_UserCenter_UserAccountLogic userAccountLogic = MS_UserCenter_UserAccountLogic.GetInstance();
            long loginUid = SecurityIdentity.GetLoginUid(Platform.BMS);
            MS_UserCenter_UserAccount userAccount = userAccountLogic.GetById(uid);
            if (userAccount == null)
            {
                model.code = Code.ERROR;
                model.message = Message.PARAMERROR;
                model.data = "未找到用户信息";
            }
            userAccount.Passformat = (int)Passformat.Encrypt;
            userAccount.Password = Utils.MD5(ConfigSetting.DefaultPassword);
            userAccount.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
            userAccount.UpdateUid = loginUid;
            userAccountLogic.Save(userAccount);
            //更新缓存
            userAccountLogic.RemoveCache(userAccount.Uid);

            model.code = Code.SUCCESS;
            model.message = Message.SUCCESS;
            model.data = new { };
            return Json(model);
        }
        #endregion
    }
}